/**
 * 
 */
package com.dfhc.pub.web;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.quickbundle.project.RmProjectHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import bsh.EvalError;

import com.dfhc.ISystemConstant;
import com.dfhc.pub.concurrencycontrol.RequestConcurrentLockException;
import com.dfhc.pub.concurrencycontrol.RequestConcurrentRoute;
import com.dfhc.pub.service.BeanShellService;
import com.dfhc.pub.service.PickMenuLinkInPageService;
import com.dfhc.pub.service.ReportProxyService;
import com.dfhc.rm.user.service.UserService;
import com.dfhc.rm.user.vo.UserVo;
import com.dfhc.util.JspHelper;
import com.dfhc.util.StringHelper;
import com.dfhc.util.TemplateHelper;


/**
 * @author longsebo
 * 测试Controller
 */
@Controller
@RequestMapping(value = "/testController")
public class TestController {
	@Autowired
	private BeanShellService beanShellService;
	@Autowired() @Qualifier("pickMenuLinkInPageService")
	private PickMenuLinkInPageService pickMenuLinkInPageService;	
	
	@Autowired() @Qualifier("reportProxyService")
	private ReportProxyService reportProxyService;
    @Autowired
    /**
     * RM_USER服务
     */
    private UserService userService;	
	/**
	 * 测试beanshell事务
	 * @throws EvalError 
	 *
	 */
    @RequestMapping(value = "testBeanShell")
    public void testBeanShell(HttpServletRequest request,HttpServletResponse response) throws EvalError {
    	
    	
    	String srciptText = "import org.activiti.service.LeaveService;" +
    			          "import org.quickbundle.base.beans.factory.RmBeanFactory;" +
    			          "import org.activiti.vo.LeaveVo;"+
    			          "import com.dfhc.util.DateUtil;"+
    			          "import org.activiti.engine.runtime.ProcessInstance;"+
    			          "import java.util.Map;"+
    			          "import java.util.HashMap;"+
    			"doSave(String userId){" +
    			" LeaveService leaveService = RmBeanFactory.getBean(LeaveService.class.getName());" +
    			" LeaveVo vo = new LeaveVo();"+
    			" vo.setUserId(userId);"+
    			" vo.setApplyTime(DateUtil.getNowDate());"+
    			" vo.setEndTime(DateUtil.getNowDate());"+
    			" vo.setLeaveType(\"请假\");"+
    			" vo.setProcessInstanceId(\"unknow\");"+
    			" vo.setRealityEndTime(DateUtil.getNowDate());"+
    			" vo.setRealityStartTime(DateUtil.getNowDate());"+
    			" vo.setReason(\"过年!\");"+
    			" vo.setStartTime(DateUtil.getNowDate());"+
    			" Map variables = new HashMap();"+
    			" leaveService.save(vo);"+
    			//" LeaveVo vo1 = null;" +
    			//" vo1.setUserId(userId);"+
    			"}";
    	        
        //BsTransaction sh;
     	String userId = RmProjectHelper.getRmUserId(request);
        //sh = (BsTransaction) BshScriptUtils.createBshObject(srciptText, new Class[] { BsTransaction.class });
        //sh.doSave(userId);
    	beanShellService.doBeanShell(userId, srciptText);
            	
    }
    /**
     * 测试请求并发锁
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "lockByGuid",consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
	public Map<String,Object>  lockByGuid(Model model,HttpServletRequest request){
    	Map<String, Object> result = new HashMap<String, Object>();
    	String jsGuid = request.getParameter(ISystemConstant.JSGUID);
    	if(StringHelper.isEmpty(jsGuid)){
    		result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
    		result.put(ISystemConstant.AJAX_MESSAGE, "缺少jsguid页面参数!");
    		return result;
    	}
    	boolean bLock = false;
    	try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(jsGuid);
	    	String sql="insert into bus_test(id) values('23234242')";
			RmProjectHelper.getCommonServiceInstance().doUpdate(sql);
			sql ="delete from bus_test where id='23234242'";
			RmProjectHelper.getCommonServiceInstance().doUpdate(sql);
			result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
			return result;
    	}finally{
   			RequestConcurrentRoute.getSingleton().unLock(jsGuid,bLock);
    	}
    }
	/**
	 * 测试标签
	 * @throws EvalError 
	 *
	 */
    @RequestMapping(value = "testTag")
    public String testTag(HttpServletRequest request,HttpServletResponse response)  {
    	return "/test/testtag";
    }
    /**
	 * 测试布局
	 *
	 */
    @RequestMapping(value = "testtempregion")
    public String testTemplateRegion(HttpServletRequest request,HttpServletResponse response)  {
    	return "/test/template/testtempregion";
    }
	/**
	 * 提取jsp菜单链接
	 * @param request
	 * @param response
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 */
    @RequestMapping(value = "pickMenu")
    public void pickMenu(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException, IOException  {
    	
    	String path="D:\\eclipse38_dev\\professional\\WebContent\\WEB-INF\\jsp\\professional\\regsys\\declareoperat";
    	List<String> menuCodeList = new ArrayList<String>();
    	
    	menuCodeList.add("101101102100");
    	menuCodeList.add("101101102104");
    	menuCodeList.add("101101102101");
    	menuCodeList.add("101101102102");
    	menuCodeList.add("101101102103");
    	menuCodeList.add("101101103100");
    	menuCodeList.add("101101103101");
    	menuCodeList.add("101101103102");
    	menuCodeList.add("101101103103");
    	menuCodeList.add("101101103104");
    	String sqlFile ="E:\\dfhc2017\\教育部考试中心\\03code\\sql\\declareoperat.sql";
    	response.setHeader("Content-type","text/html;charset=UTF-8");//向浏览器发送一个响应头，设置浏览器的解码方式为UTF-8  
    	OutputStream stream = response.getOutputStream();  
    	try {
			pickMenuLinkInPageService.doPickMenu(path, menuCodeList, sqlFile);
			stream.write("生成成功!".getBytes(ISystemConstant.ENCODE_UTF_8));
		} catch (Exception e) {
			e.printStackTrace();
			stream.write("生成失败!".getBytes(ISystemConstant.ENCODE_UTF_8));
			stream.write(e.getMessage().getBytes(ISystemConstant.ENCODE_UTF_8));
		}
 	    stream.close();    	
    }    
    
    
    /**
     * 报表下载(测试方法)
     * @param request
     * @param response
     * @throws Exception 
     */
    @RequestMapping(value = "testReportGenerate")
    public void testTemplate(HttpServletRequest request,HttpServletResponse response)throws Exception  {
    	Map<String,Object> parameters =new HashMap<String,Object>();
    	reportProxyService.download("002", "01", "123", parameters, response);
    	
    	OutputStream stream = response.getOutputStream();  
    	try {
			stream.write("生成成功!".getBytes(ISystemConstant.ENCODE_UTF_8));
		} catch (Exception e) {
			e.printStackTrace();
			stream.write("生成失败!".getBytes(ISystemConstant.ENCODE_UTF_8));
			stream.write(e.getMessage().getBytes(ISystemConstant.ENCODE_UTF_8));
		}
 	    stream.close();    
    }
    
    
    /**
     * 报表浏览器查看(测试方法)
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "testReportGenerate2")
    public void testTemplate2(HttpServletRequest request,HttpServletResponse response)throws Exception  {
    	Map<String,Object> parameters =new HashMap<String,Object>();
    	reportProxyService.viewReport("002", ISystemConstant.DICTIONARY_REPORT_TYPE_03, "0328", parameters, response);
    	
//    	OutputStream stream = response.getOutputStream();  
//    	try {
//			stream.write("生成成功!".getBytes(ISystemConstant.ENCODE_UTF_8));
//		} catch (Exception e) {
//			e.printStackTrace();
//			stream.write("生成失败!".getBytes(ISystemConstant.ENCODE_UTF_8));
//			stream.write(e.getMessage().getBytes(ISystemConstant.ENCODE_UTF_8));
//		}
// 	    stream.close();    
    }
    @RequestMapping(value="testRedirectA")
    public String testRedirectA(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
    	request.getRequestDispatcher("/testController/testRedirectB").forward(request,response);
    	return "/test/redirect/a";
    }
    @RequestMapping(value="testRedirectB")
    public void testRedirectB(HttpServletRequest request,HttpServletResponse response) throws IOException{
    	//System.out.println("template:"+request.getParameter("template"));
    	String compayName=request.getParameter("companyName");
    	String template;
    	if(compayName.equalsIgnoreCase("电力医院")){
    		template= "D:\\tmp\\a.ftl";
    	}else{
    		template= "D:\\tmp\\b.ftl";
    	}
    	Map<String,Object> paramMap = new HashMap<String,Object>();
    	paramMap.put("companyName", compayName);
    	String html = TemplateHelper.createContentByPath(paramMap, template);
    	response.setHeader("Content-type","text/html;charset=UTF-8");//向浏览器发送一个响应头，设置浏览器的解码方式为UTF-8  
    	response.getWriter().print(html);
    	response.getWriter().flush();
    	response.getWriter().close();
    	
    }
    /**
     * html打印
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value="printhtml")
    public String printhtml(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{    	
    	return "/test/printhtml/testwebsocket";
    }    
    /**
     * ajax 请求列表数据
     * @param model
     * @param request
     * @return
     * @throws IOException 
     */
    @RequestMapping(value = "ajaxUserList",  produces="application/json")
    @ResponseBody
    public Map<String,Object> ajaxUserList(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException{
           Map<String,Object> dataMap=new HashMap<String,Object>();
           try{
		        //获取开始记录数
		        String startRow = request.getParameter(ISystemConstant.PAGE_START_KEY);
		        String rows=request.getParameter(ISystemConstant.PAGE_SIZE_KEY)==null?ISystemConstant.DEFAULT_PAGE_SIZE:request.getParameter(ISystemConstant.PAGE_SIZE_KEY);	        
		        int rowsInt=Integer.parseInt(rows);//页大小
		        if(StringHelper.isEmpty(startRow)){
		        	startRow="0";
		        }
		        int startRowInt = Integer.parseInt(startRow);
		        Map<String, Object> searchPara = new HashMap<String,Object>();
		        int totalNum = userService.getCount(searchPara);
		        String orderStr = JspHelper.getOrderStr(request);  //得到排序信息
	        
	        	List<UserVo> beans = userService.list(searchPara, orderStr, startRowInt+1, rowsInt);  //按条件查询全部,带排序
	        	//翻译状态码
	        	if(beans!=null){
	        	for(UserVo bean:beans){
				//如果状态码字段有其他用途，请用扩展字段attribute1-attribute5代替
	        	}
	        	}         
	        	dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
		        dataMap.put(ISystemConstant.PAGE_DRAW, request.getParameter(ISystemConstant.PAGE_DRAW));
	        	dataMap.put(ISystemConstant.RECORDS_TOTAL,totalNum);
		        dataMap.put(ISystemConstant.RECORDS_FILTERED, totalNum);
	        	dataMap.put(ISystemConstant.DATA, beans);
	        	return dataMap;
          }catch(RequestConcurrentLockException e){
        	  RmProjectHelper.logInf(StringHelper.exceptionToString(e));
        	  dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
        	  dataMap.put(ISystemConstant.AJAX_MESSAGE, e.getMessage());
        	  return dataMap;   
          }catch(Exception e){
        	  e.printStackTrace();
        	  RmProjectHelper.logInf(StringHelper.exceptionToString(e));
        	  dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
        	  dataMap.put(ISystemConstant.AJAX_MESSAGE, "查询失败!");
        	  return dataMap;
          }
    }    
}
